package com.example.springboot.service;

import com.example.springboot.bean.Department;
import com.example.springboot.mapper.DepartmentMapper;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.Future;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/10/22 21:37
 */
@Service
@Slf4j
// 可以在类上指定缓存管理器
@CacheConfig(cacheManager = "deptCacheManager", cacheNames = "dept")
public class DeptService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Cacheable(cacheNames = "{emp}")
    public Department getDeptById(Integer id) {
        System.out.println("查询部门 " + "id");
        Department department = departmentMapper.getById(id);
        return department;
    }

    @Autowired
    @Qualifier(value = "deptCacheManager")
    private RedisCacheManager cacheManager;

    /**
     * 编码方式使用缓存管理器,但是springboot2.0以上试验后都是查询数据库，虽然redis中有缓存
     *
     * @param id
     * @return
     */
    public Department getDeptById_1(Integer id) {
        System.out.println("查询部门 " + "id");
        Department department = departmentMapper.getById(id);
        Cache dept = cacheManager.getCache("dept");
        dept.put("dept_key", department);
        return department;
    }
    public List<Department> queryByIds(List<Integer> ids){
        List<Department> list=departmentMapper.findByIds(ids);
        return list;
    }

    public void insertDept(Department department) {
        departmentMapper.insertDept(department);
    }

    @HystrixCollapser(batchMethod = "findDepartmentByIds", scope = com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL,
            collapserProperties = {
                    @HystrixProperty(name = "batchMerge", value = "10")
            })
    public Future<Department> getById(int id) {
        return null;
    }

    @HystrixCommand
    public List<Department> findDepartmentByIds(List<Integer> ids) {
        log.info("【===进入查询接口，参数{}====】", ids);
        return queryByIds(ids);
    }
}
